import axios, { type AxiosResponse, type AxiosRequestConfig } from "axios";
import cookie from "js-cookie";
import qs from "qs";
import router from "@/router";
import { ElMessage, } from 'element-plus' //消息提示
import { useUserStore } from "@/stores/admin/Index";
import nprogress from "nprogress";

declare interface TypResponse extends AxiosResponse {
    /**
     * 错误号，200表示成功
     */
    errno: number,
    /**
     * 返回的类型
     */
    errmsg: string

    url: string
}


let baseURL = '';

// 判断登录环境
if (process.env.NODE_ENV === 'development') {//开发环境
    baseURL = '/m.api'
} else {//上线
    baseURL = 'http://192.168.1.188:8080/m.api'
}

const instance = axios.create({
    baseURL,
    headers: {
        "content-type": 'application/x-www-form-urlencoded'
    }
})

// 添加请求拦截器
instance.interceptors.request.use(function (config: AxiosRequestConfig) {
    if (config.headers) {
        config.headers['AdminToken'] = cookie.get('token') + ''
        nprogress.start()
    }
    return config
}, function (error) {
    console.log('请求错误', error);
    return Promise.reject(error)
})

const METHOD_TYPE = ['_mt=edit', '_mt=create', "_mt=delete"]

// 添加响应拦截器
instance.interceptors.response.use(async function (response: AxiosResponse) {
    let data = response.data//数据浅解
    let { errno, errmsg } = data
    let path = router.currentRoute.value.fullPath

    if (10006 === errno) {//判断是否登录过期
        // 获取接口请求数据
        const confing_Data = response.config.data || ''

        // 请求类型是否为无痛刷新 index!=-1 需要无痛刷新令牌
        var index = METHOD_TYPE.findIndex(item => confing_Data.includes(item))

        if (-1 == index) {//重新登录获取令牌
            router.replace({
                path: '/login',
                query: { back: path }//登录后需要跳回的地址
            })
            ElMessage.error(errmsg)
            return
        } else {//需要无痛刷新令牌
            const store = useUserStore()
            const { username, password } = store.user

            // 重新获取令牌
            let loginData = { _gp: "admin", _mt: "login", username: username, password: password, }
            const { errmsg, errno, data } = await post(loginData)//同步获取去请求
            if (200 == errno) {
                cookie.set("token", data)//保存token
            } else {
                router.replace({path: '/login',query: { back: path }})//登录后需要跳回的地址
                return Promise.reject({errno,errmsg,data})
            }
            return instance.request(response.config)
        }
    }
    nprogress.done()
    return data;
}, function (error) {
    // 对响应错误做点什么
    console.error("请求响应错误", error)
    return Promise.reject(error);
})

function get(params?: object): Promise<TypResponse> {
    return instance.get("", { params })
}

function post(data: object, params?: object): Promise<TypResponse> {
    return instance.post("", qs.stringify(data), { params })
}

export {
    get,
    post
}

// 富文本图片请求
export function upload(data: object): Promise<TypResponse> {
    return instance.post("../upload/admin", data);
}